#2020-11-28000
import logging
import os
import time
import shutil
import datetime

from os.path import join,getsize


USB = 'F:\\Pictures'  # u盘目录
SAVE = 'E:\\LSY_U_copy'  # 保存目录

def my_logging(message,string):
    today = datetime.date.today()
    logging.basicConfig(level=logging.DEBUG,#控制台打印的日志级别
                        filename=str(today)+'new.log',
                        filemode='a',##模式，有w和a，w就是写模式，每次都会重新写日志，覆盖之前的日志
                        #a是追加模式，默认如果不写的话，就是追加模式
                        format=
                        '%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s'
                        #日志格式
                        )
    if(message=='debug'):
        logging.debug(string)
    elif(message == 'info'):
        logging.info(string)
    elif(message=='warning'):
        logging.warning(string)
    elif(message=='error'):
        logging.error(string)
    elif(message=='critial'):
        logging.critical(string)


def main():
    while (1):
        if os.path.exists(USB):
            my_logging("warning","检测到LSY的U盘插入，备份程序开始！")
            dirs = os.listdir(USB)
            U_dirs = sorted(dirs)
            C_dirs = sorted(os.listdir(SAVE))
            i = 0
            j = 0
            if len(C_dirs) == 0 :
                while i < len(U_dirs):
                    temp1 = USB + "\\" + U_dirs[i]
                    temp2 = SAVE + "\\" + U_dirs[i]
                    open(temp2, "wb").write(open(temp1, "rb").read())
                    i+=1


            while(i != len(dirs)):
                if U_dirs[i] == C_dirs[j]:
                    i+=1
                    j+=1
                else:
                    temp1 = USB + "\\" + U_dirs[i]
                    temp2 = SAVE + "\\" + U_dirs[i]
                    open(temp2, "wb").write(open(temp1, "rb").read())
                    i+=1
                    my_logging("warning","更新一个新文件#"+temp1)
        else:
            my_logging("debug","暂时没有U盘")
        my_logging("debug","开始休眠")
        time.sleep(30)  # 休眠时间
        my_logging("debug", "休眠结束")
if __name__ == "__main__":
    main()